﻿# coding:utf-8
import re
import time
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
import datetime
d = datetime.date.today()
m = d.month
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.base import MIMEBase
from email import encoders
import mimetypes, os
from Logs.log import log1
from utils import select_result, to_adds, save_zip_files, update_po, e1, s0
import datetime



def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))


def annex(path):
    try:
        data = open(path, 'rb')
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            ctype = 'application/x-zip-compressed'
        maintype, subtype = ctype.split('/', 1)
        file_msg = MIMEBase(maintype, subtype)
        file_msg.set_payload(data.read())
        data.close()
        encoders.encode_base64(file_msg)
        basename = os.path.basename(path)
        file_msg.add_header('Content-Disposition', 'attachment', filename=basename)
        return file_msg
    except:
        log1.error('添加文件失败！')


def run(po_list):
    # 发件人地址
    from_addr = 'sys_eip@szhorn.com'
    # 邮箱密码
    password = 'Aa666666'
    # 收件人地址
    to_addr = to_adds()[0]
    cc = to_adds()[1:]
    toaddrs = [to_addr] + cc
    # 邮箱服务器地址
    smtp_server = 'smtp.exmail.qq.com'
    # 设置邮件信息
    today = datetime.date.today()
    today_str = today.strftime("%Y-%m-%d")
    msg = MIMEMultipart()
    # msg.add_header('From', 'sys_dev <%s>' % from_addr)
    # msg.add_header('To', to_addr)
    # msg.add_header('Cc', ','.join(cc))
    po_name = ""
    for po in po_list:
        files = save_zip_files
        file_dir = os.path.join(files, po)
        files = os.listdir(file_dir)
        master_file = ""
        master_name = ""
        txn_file = ""
        txn_name = ""
        for file in files:
            if re.search(r"MASTER", file):
                master_file = os.path.join(file_dir, file)
                master_name = file
            elif re.search(r"TXN", file):
                txn_file = os.path.join(file_dir, file)
                txn_name = file
        if not (master_file and txn_file):
            try:
                QUERY_RESULT, QTY, UPLOAD_STATUS, UPLOAD_RESULT = select_result(po)
                if QUERY_RESULT and QUERY_RESULT != "OK":
                    po_name += "PO号{}(EIP导出失败:{})\n".format(po, QUERY_RESULT)
                else:
                    po_name += "PO号{}(EIP导出失败: 详情不知,请联系相关人员)\n".format(po)
            except:
                po_name += "PO号{}(EIP导出失败:无此PO号维护信息)\n".format(po)
            msg['Subject'] = Header('<{}>PO号{}上传情况反馈_自动导出TestMaser/Txn数据文件_TEST(导出失败)'.format(today_str, po_list[0]), 'utf-8').encode()
            continue
        msg.add_header('From', 'sys_dev <%s>' % from_addr)
        msg.add_header('To', to_addr)
        msg.add_header('Cc', ','.join(cc))
        po_name += "PO号{}(EIP导出成功:{},{})\n".format(po, master_name, txn_name)
        msg['Subject'] = Header('<{}>PO号{}上传情况反馈_自动导出TestMaser/Txn数据文件_TEST(导出成功)'.format(today_str, po_list[0]), 'utf-8').encode()
        imageApart0 = MIMEImage(open(master_file, 'rb').read(), master_file.split('.')[-1])
        imageApart0.add_header('Content-Disposition', 'attachment', filename=master_name)
        imageApart1 = MIMEImage(open(txn_file, 'rb').read(), txn_file.split('.')[-1])
        imageApart1.add_header('Content-Disposition', 'attachment', filename=txn_name)
        msg.attach(imageApart0)
        msg.attach(imageApart1)
    mail = "EIP导出的文件详见附件:\n" + po_name
    textApart = MIMEText(mail, 'plain', 'utf-8')
    msg.attach(textApart)
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.login(from_addr, password)
    server.sendmail(from_addr, toaddrs, msg.as_string())
    server.quit()


